import time
import logging
from datetime import datetime
from pyChrome import PyChrome

"""
自动监控有价值项目的消息
PyChrome doc:
https://pychrome.wordpress.com/usage/
"""
logging.basicConfig(format="%(thread)d %(asctime)s %(name)s:%(levelname)s:%(lineno)d:%(message)s",
                    datefmt="%Y-%m-%d %H:%M:%S", level=logging.DEBUG)
browser = PyChrome()
logger = logging.getLogger(__name__)


def login(username, password):
    # 登录
    global browser
    browser.open("https://github.com/login")
    # name="login"
    name_locator = "//*[@name='login']"
    el_name = browser.findElementByXPath(name_locator)
    browser.sendTextToElement(username, el_name)
    # name="password"
    pass_locator = "//*[@name='password']"
    el_pass = browser.findElementByXPath(pass_locator)
    browser.sendTextToElement(password,el_pass)
    login_locator = "//*[@name='commit']"
    el_login = browser.findElementByXPath(login_locator)
    browser.clickElement(el_login)
    # time.sleep(1)
    logger.debug("login github")


def get_repos():
    global browser
    browser.open("https://github.com/notifications")
    # 获取有消息的Repositories列表
    locator = "js-notification-sidebar-repositories"
    el_repos = browser.findElementByClass(locator)
    repos_list = browser.findElementsByTag("li", el_repos)
    logger.debug("get repos_list: " + str(len(repos_list)))
    return repos_list


def get_timedelta(repos_name, unsubscribe=True):
    global browser
    # https://github.com/instacart/lore/pulls?q=
    browser.newTab("https://github.com/" + repos_name + "/pulls?q=")
    # 判断最近的 pull request
    locator = "//div[@aria-label='Issues']"
    el_pulls = browser.findElementByXPath(locator)
    pull_list = browser.findElementsByTag("relative-time", el_pulls)
    timedelta = 0
    if type(pull_list)==list and len(pull_list)>0:
        # 2020-11-10T00:55:39Z
        # last_pull_time_str = pull_list[0].getAttribute("datetime")
        last_pull_time_str = pull_list[0].get_attribute("datetime")
        last_time = datetime.strptime(last_pull_time_str, "%Y-%m-%dT%H:%M:%SZ")
        timedelta = (datetime.now() - last_time).days
    logger.debug(repos_name + " timedelta: " + str(timedelta) + " days")
        # 取消不活跃项目的订阅(1年以上没有pull request)
    if unsubscribe and timedelta > 366:
        el_notify_button = browser.findElementsByTag("notifications-list-subscription-form")
        browser.clickElement(el_notify_button)
        time.sleep(1)
        # data-target="notifications-list-subscription-form.menu"
        locator = "//*[@data-target='notifications-list-subscription-form.menu']"
        el_notify_menus = browser.findElementByXPath(locator)
        # value="ignore"
        sub_locator = "//*[@value='ignore']"
        el_ignore_button = browser.findElementByXPath(sub_locator, el_notify_menus)
        browser.clickElement(el_ignore_button)
        logger.debug(repos_name + " cancel subscribed")
        time.sleep(1)
    browser.closeTab()
    return timedelta


if __name__=="__main__":
    login("showkeyjar", "******")
    repos_list = get_repos()
    while len(repos_list)>0:
        no_use = True
        repos = repos_list[0]
        repos_name = repos.text.strip()
        msg_num = browser.findElementByTag("span", repos).text.strip()
        repos_name = repos_name[len(msg_num):].strip()
        timedelta = get_timedelta(repos_name)
        if no_use:
            # 清除不活跃项目的通知
            el_repos_link = browser.findElementByTag("a", repos)
            browser.clickElement(el_repos_link)
            # mr-1 js-notifications-mark-all-prompt
            time.sleep(1)
            el_sel_all = browser.findElementByClass("js-notifications-mark-all-prompt")
            browser.clickElement(el_sel_all)
            time.sleep(1)
            # title="Done"
            done_locator = "//*[@title='Done']"
            el_done = browser.findElementByXPath(done_locator)
            browser.clickElement(el_done)
            logger.debug(repos_name + " remove notifiy")
            time.sleep(1)
            repos_list = get_repos()
        logger.debug("proceed " + repos_name)
    logger.debug("all finished")
